/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// 后序遍历(dfs)+计算节点到叶子距离：叶子节点为0，父节点=max(left, right)+1，同一深度为一组。
func findLeaves(root *TreeNode) [][]int {
	if root == nil {
		return nil
	}

	res = nil
	dfs(root)
	return res
}

var res [][]int

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func dfs(root *TreeNode) int {
	if root == nil {
		// 这样的话，叶子节点深度即为0
		return -1
	}

	left := dfs(root.Left)
	right := dfs(root.Right)

	cur := max(left, right) + 1

	if cur >= len(res) {
		var temp []int
		temp = append(temp, root.Val)
		res = append(res, temp)
	} else {
		res[cur] = append(res[cur], root.Val)
	}

	return cur
}